package com.xneure.ilog.views;

import java.lang.reflect.Field;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.model.RuntimeProcess;

public class EDebugEvent implements IDebugEventSetListener{
	private Process currProcess;
	private LogCallBack lcb;
	Thread thread = new Thread(new Runnable(){
		@Override
		public void run(){
			try{
				currProcess.waitFor();
			}catch(InterruptedException e){
				e.printStackTrace();
			}finally{
				currProcess = null;
			}
		}
	});

	public EDebugEvent(LogCallBack lcb){
		this.lcb = lcb;
	}

	public void handleDebugEvents(DebugEvent[] events){
		if(null == currProcess && events[0].getSource() instanceof RuntimeProcess){
			RuntimeProcess rp = (RuntimeProcess)events[0].getSource();
			try{
				if(null == rp.getStreamsProxy()){
					return;
				}
				lcb.call("",null);
				rp.getStreamsProxy().getOutputStreamMonitor().addListener(new LogProcessor(lcb,LogLevel.DEBUG));
				rp.getStreamsProxy().getErrorStreamMonitor().addListener(new LogProcessor(lcb,LogLevel.ERROR));
				Field field = rp.getClass().getDeclaredField("fProcess");
				field.setAccessible(true);
				boolean isLast = null == currProcess;
				currProcess = (Process)field.get(rp);
				field.setAccessible(false);
				if(null != currProcess){
					if(isLast){
						thread.start();
					}else{
						thread.run();
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
